package cn.jdx.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        //第一次表单的请求需要放行！
        String requestURI = request.getRequestURI();
        System.out.println("[URI]:"+requestURI);

        if(requestURI.contains("user/toLoginSuccess")){//访问login_success.jsp需要拦截
            if(session.getAttribute("countInfo") != null){//已经登录了就放行
                return true;
            }else{
                //如果拦截了，就转发
                response.sendRedirect(request.getContextPath()+"/user/toLogin");
                System.out.println("[拦截器]:用户直接访问登录界面被拦截");
                return false;
            }
        }


        if(requestURI.contains("user/toLogin")){//访问login.jsp需要放行
            return true;
        }


        if (requestURI.contains("user/login")){//第一次提交登录的时候
            return true;
        }

        return false;
    }
}
